#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# @Time    : 2025/9/28 15:30
# @Author  : WXY
# @File    : HistoryManager.py
# @PROJECT_NAME: youtubedown_gui
# @PRODUCT_NAME: PyCharm
# -------------------------------------------------------------------------------

import json
import os
import threading
import random
from datetime import datetime, timedelta
from dataclasses import dataclass, asdict
from typing import List, Dict, Any, Optional
from LoggerManager import logger_manager


@dataclass
class HistoryRecord:
    """历史记录数据类"""
    url: str  # 视频URL
    title: str  # 视频标题/文件名
    status: str  # 下载状态
    download_path: str  # 下载路径
    download_time: str  # 下载时间
    limit_resolution: Optional[str]  # 分辨率限制（None=不限制，"360"="360p"，"720"="720p"等）
    mp4_only: bool  # 是否只下载mp4

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return asdict(self)

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'HistoryRecord':
        """从字典创建对象"""
        return cls(**data)


class HistoryManager:
    """历史记录管理器"""

    def __init__(self, max_records: int = 100):
        self.max_records = max_records
        # 类型注解, 这有点像
        self.history_records: List[HistoryRecord] = []
        self.history_file = "history.json"
        self._lock = threading.Lock()

    def initialize(self):
        """初始化历史记录管理器"""
        try:
            self.ensure_history_file_exists()
            self.load_from_file()
            logger_manager.info("历史记录管理器初始化完成", "history_manager")
        except Exception as e:
            logger_manager.error(f"历史记录管理器初始化失败: {e}", "history_manager")

    def ensure_history_file_exists(self):
        """确保历史记录文件存在"""
        try:
            if not os.path.exists(self.history_file):
                # 创建空的历史记录文件
                with open(self.history_file, 'w', encoding='utf-8') as f:
                    json.dump([], f, ensure_ascii=False, indent=2)
                logger_manager.info(f"创建历史记录文件: {self.history_file}", "history_manager")
            else:
                logger_manager.debug(f"历史记录文件已存在: {self.history_file}", "history_manager")
        except Exception as e:
            logger_manager.error(f"创建历史记录文件失败: {e}", "history_manager")

    def load_from_file(self):
        """从文件加载历史记录"""
        try:
            if not os.path.exists(self.history_file):
                self.history_records = []
                return

            with open(self.history_file, 'r', encoding='utf-8') as f:
                data = json.load(f)

            self.history_records = []
            for item in data:
                try:
                    record = HistoryRecord.from_dict(item)
                    self.history_records.append(record)
                except Exception as e:
                    logger_manager.warning(f"跳过无效的历史记录项: {e}", "history_manager")

            # 保持最大记录数限制
            if len(self.history_records) > self.max_records:
                self.history_records = self.history_records[-self.max_records:]

            logger_manager.info(f"加载了 {len(self.history_records)} 条历史记录", "history_manager")

        except json.JSONDecodeError as e:
            logger_manager.error(f"历史记录文件格式错误: {e}", "history_manager")
            self.history_records = []
        except Exception as e:
            logger_manager.error(f"加载历史记录失败: {e}", "history_manager")
            self.history_records = []

    def add_record(self, url: str, title: str, status: str, download_path: str,
                   limit_resolution: Optional[str] = None, mp4_only: bool = False):
        """添加新的历史记录"""
        try:
            with self._lock:
                # 创建新记录
                record = HistoryRecord(
                    url=url,
                    title=title,
                    status=status,
                    download_path=download_path,
                    download_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    limit_resolution=limit_resolution,
                    mp4_only=mp4_only
                )

                # 检查是否已存在相同URL的记录，如果存在则更新
                existing_index = -1
                for i, existing_record in enumerate(self.history_records):
                    if existing_record.url == url:
                        existing_index = i
                        break

                if existing_index >= 0:
                    # 更新现有记录
                    self.history_records[existing_index] = record
                    logger_manager.debug(f"更新历史记录: {url}", "history_manager")
                else:
                    # 添加新记录
                    self.history_records.append(record)
                    logger_manager.debug(f"添加新历史记录: {url}", "history_manager")

                # 保持最大记录数限制
                if len(self.history_records) > self.max_records:
                    self.history_records = self.history_records[-self.max_records:]

        except Exception as e:
            logger_manager.error(f"添加历史记录失败: {e}", "history_manager")

    def get_all_records(self) -> List[HistoryRecord]:
        """获取所有历史记录"""
        with self._lock:
            return self.history_records.copy()

    def update_record_status(self, url: str, status: str):
        """更新记录状态"""
        try:
            with self._lock:
                for record in self.history_records:
                    if record.url == url:
                        record.status = status
                        logger_manager.debug(f"更新记录状态: {url} -> {status}", "history_manager")
                        break
        except Exception as e:
            logger_manager.error(f"更新记录状态失败: {e}", "history_manager")

    def remove_record(self, url: str):
        """删除记录"""
        try:
            with self._lock:
                self.history_records = [record for record in self.history_records if record.url != url]
                logger_manager.debug(f"删除历史记录: {url}", "history_manager")
        except Exception as e:
            logger_manager.error(f"删除历史记录失败: {e}", "history_manager")

    def clear_all_records(self):
        """清空所有记录"""
        try:
            with self._lock:
                self.history_records.clear()
                logger_manager.info("清空所有历史记录", "history_manager")
        except Exception as e:
            logger_manager.error(f"清空历史记录失败: {e}", "history_manager")

    def save_to_file(self):
        """保存历史记录到文件"""
        try:
            with self._lock:
                data = [record.to_dict() for record in self.history_records]

            with open(self.history_file, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)

            logger_manager.debug(f"保存了 {len(self.history_records)} 条历史记录到文件", "history_manager")

        except Exception as e:
            logger_manager.error(f"保存历史记录失败: {e}", "history_manager")

    def generate_test_data(self):
        """生成测试数据"""
        try:
            video_urls = [
                "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
                "https://www.youtube.com/watch?v=kJQP7kiw5Fk",
                "https://www.youtube.com/watch?v=9bZkp7q19f0",
                "https://www.youtube.com/watch?v=fJ9rUzIMcZQ",
                "https://www.youtube.com/watch?v=YQHsXMglC9A",
                "https://www.youtube.com/watch?v=hTWKbfoikeg",
                "https://www.youtube.com/watch?v=JGwWNGJdvx8",
                "https://www.youtube.com/watch?v=uelHwf8o7_U",
                "https://www.youtube.com/watch?v=L_jWHffIx5E",
                "https://www.youtube.com/watch?v=CevxZvSJLk8"
            ]

            video_titles = [
                "Rick Astley - Never Gonna Give You Up.mp4",
                "Luis Fonsi - Despacito ft. Daddy Yankee.mp4",
                "BLACKPINK - How You Like That.mp4",
                "Maroon 5 - Sugar.mp4",
                "Katy Perry - Roar.mp4",
                "LearnCode.academy - JavaScript Tutorial.mp4",
                "Sia - Chandelier.mp4",
                "Ed Sheeran - Shape of You.mp4"
            ]

            status_list = ["已完成", "下载失败", "下载中", "已取消"]
            download_paths = [
                "D:\\Downloads\\Videos\\",
                "D:\\Downloads\\Music\\",
                "C:\\Users\\Downloads\\",
                "E:\\Media\\Videos\\",
                "D:\\MyVideos\\YouTube\\"
            ]

            # 分辨率选项：None表示不限制，字符串表示具体分辨率
            resolution_options = [None, "360", "720", "1080", "2160"]

            with self._lock:
                self.history_records.clear()

                for i in range(20):
                    # 生成随机数据
                    url = random.choice(video_urls)
                    title = random.choice(video_titles)
                    status = random.choice(status_list)
                    path = random.choice(download_paths)
                    limit_resolution = random.choice(resolution_options)
                    mp4_only = random.choice([True, False])

                    # 生成随机时间（最近30天内）
                    current_time = datetime.now()
                    random_days = random.randint(0, 30)
                    random_seconds = random.randint(0, 86400)
                    random_time = current_time - timedelta(days=random_days, seconds=random_seconds)
                    time_str = random_time.strftime("%Y-%m-%d %H:%M:%S")

                    record = HistoryRecord(
                        url=url,
                        title=title,
                        status=status,
                        download_path=path,
                        download_time=time_str,
                        limit_resolution=limit_resolution,
                        mp4_only=mp4_only
                    )

                    self.history_records.append(record)

                logger_manager.info("生成测试数据完成", "history_manager")

        except Exception as e:
            logger_manager.error(f"生成测试数据失败: {e}", "history_manager")

    def update_record_title(self, url: str, title: str):
        """更新记录标题"""
        try:
            with self._lock:
                for record in self.history_records:
                    if record.url == url:
                        record.title = title
                        logger_manager.debug(f"更新记录标题: {url} -> {title}", "history_manager")
                        break
        except Exception as e:
            logger_manager.error(f"更新记录标题失败: {e}", "history_manager")

# 全局历史记录管理器实例
history_manager = HistoryManager()